package org.example.util;


import io.minio.*;
import io.minio.errors.*;
import io.minio.http.Method;
import io.minio.messages.Item;
import lombok.RequiredArgsConstructor;
import org.example.dao.Dynamic;
import org.example.dao.Song;
import org.example.dao.User;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;


@RequiredArgsConstructor
@Component
public class MinioUtil {

    //minio
    private final MinioClient minioClient;


    //为歌曲添加url
    public void getSongUrl(List<Song> songList) {
        songList.forEach(song -> {
            song.setUrl(getFileUrl("song", song.getUrl()));
            song.setImg(getFileUrl("songimg", song.getImg()));
        });
    }

    //获取一个桶中的所有文件名
    public ArrayList<String> getSong(String songName) {
        ArrayList<String> list = new ArrayList<>();
        Iterable<Result<Item>> datas = minioClient.listObjects(ListObjectsArgs.builder()
                .bucket(songName)
                .build());
        datas.forEach(itemResult -> {
            try {
                String s = itemResult.get().objectName();
                list.add(s);
                System.out.println(s);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });
        return list;
    }

    //根据桶名和文件名，获取可以访问的url
    private String getFileUrl(String bucketName, String songName) {
        try {
            return minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
                    .bucket(bucketName)
                    .object(songName)
                    .method(Method.GET)
                    .build());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 设置用户头像
     *
     * @param userId 用户ID
     * @param file   用户上传的头像文件
     */
    public String setUserHeadImage(String userId, MultipartFile file) {
        String hz = getHZ(file.getOriginalFilename());
        // 尝试上传文件到MinIO
        try {
            // 使用MinIO客户端将文件上传到"userheadimage"桶中
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket("userheadimage")
                    .object(userId + hz)
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .build()
            );
            return userId + hz;
        } catch (Exception e) {
            // 如果发生异常，抛出运行时异常
            throw new RuntimeException(e);
        }

    }

    /**
     * 设置动态图片
     */
    public String setDynamicImage(MultipartFile file) {
        // 获取文件原始名称
        String hz = getHZ(file.getOriginalFilename());
        // 尝试上传文件到MinIO
        try {
            String imageName = UUID.randomUUID().toString() + new Date().getTime();

            // 使用MinIO客户端将文件上传到"userheadimage"桶中
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket("dynamicimage")
                    .object(imageName + hz)
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .build()
            );
            return imageName + hz;
        } catch (Exception e) {
            // 如果发生异常，抛出运行时异常
            throw new RuntimeException(e);
        }

    }

    //为歌曲添加url
    public void getDynamicUrl(List<Dynamic> dynamics) {
        dynamics.forEach(dynamic -> {
            String images = dynamic.getImage();
            if (images == null) {
                return;
            }
            String[] split = images.split(";");
            ArrayList<String> urls = new ArrayList<>();
            for (String im : split) {
                urls.add(getFileUrl("dynamicimage", im));
            }
            dynamic.setImages(urls);
        });
    }

    //为用户头像添加Url
    public void getUserHeadImageUrl(User user) {

        String headImage = user.getHeadImage();
//        System.out.println("he11111"+headImage);
//        //获取文件后缀
//        String hz = getHZ(headImage);

        String url = getFileUrl("userheadimage", headImage);
        user.setHeadImage(url);
    }


    private String getHZ(String fileName) {
        String hz = null;
        // 检查文件名是否为空
        if (fileName != null) {
            // 提取文件扩展名
            hz = fileName.substring(fileName.lastIndexOf('.'));
        }
        return hz;
    }


}
